package cn.com.libertymutual.core.security.token;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.com.libertymutual.core.exception.AppException;
import cn.com.libertymutual.core.exception.LangExceptionEnums;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.web.util.RequestUtils;

import com.google.common.base.Strings;

public class FrontSecurityCheck implements IFrontSecurityCheck {
	private Logger log = LoggerFactory.getLogger(getClass());
	
	private List<String> ignoreUrl;
	
	public FrontSecurityCheck() {

	}

	public List<String> getIgnoreUrl() {
		return ignoreUrl;
	}

	public void setIgnoreUrl(List<String> ignoreUrl) {
		this.ignoreUrl = ignoreUrl;
	}

	@Override
	public void checkToken() throws AppException {
		
		ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes());
		if( servletRequestAttributes == null ) {
			return;
		}
		
		HttpServletRequest request = servletRequestAttributes.getRequest();
		//排除校验的请求，不要乱加，出了问题自己负责
		if( ignoreUrl != null && ignoreUrl.contains( RequestUtils.getPath(request) ) ) return;
		
		HttpSession session = request.getSession(true);
		
		String tokenId = (String) session.getAttribute(Constants.USER_INFO_TOKEN_KEY);
		
		if( !Strings.isNullOrEmpty( tokenId ) ) {
			String tkId = RequestUtils.getHeaderTokenId();

			if( !tokenId.equals( tkId ) ) {
				String oldToken = (String)session.getAttribute(Constants.USER_INFO_TOKEN_KEY_OLD);
				
				if( !Strings.isNullOrEmpty( oldToken ) && oldToken.equals( tkId ) ) {
					return;
				}

				log.error("Token校验错误,"+tkId+":"+tokenId);
				throw new AppException(LangExceptionEnums.SECURITY_TOKEN_EXCEPTION, LangExceptionEnums.SECURITY_TOKEN_EXCEPTION.getMessage());
			}	
		}
	}
}
